define(['require'], function(require) {
		var BusinessDetailConfigController = Ember.Controller.extend({
			needs: ["businessDetail"],

			business: Ember.computed.alias('controllers.businessDetail.model'),

			businessChange: Ember.observer("business", function() {
				this.resetForm();
				this.requireThresholds();
			}),

			init: function() {
				var ctrl = this;
				ctrl.set("cancelSet", true);
				if (overviewOrCenterSwitch == "business") {
					ctrl.set("isShowSystemOrBusiness", false);
				} else {
					ctrl.set("isShowSystemOrBusiness", true);
				}
				this.set("alarmTimeSlot", this.get("alarmStartTime") + " - " + this.get("alarmEndTime"));
			},

			alarmStartTime: '00:00:00',
			alarmEndTime: '23:59:59',

			//初始化时加载后台告警时间
			initOnloadTime: function(validTime, name) {
				$('#businessDetailView .apm-nav-tabs-left .nav-tabs').css({
					'padding-top':0
				});
				var arr = validTime[name].split("-");
				this.set("alarmStartTime", arr[0]);
				this.set("alarmEndTime", arr[1]);
			},

			defaultAlarmTime: function(validTime) {
				var ctrl = this,
					alarmStartTime = this.get("alarmStartTime"),
					alarmEndTime = this.get("alarmEndTime");
				ctrl.set("validTimeReturn", validTime);
				for (var name in validTime) {
					switch (name) {
						case "1":
							$(".alarm-time-day span:eq(0)").addClass("active");

							ctrl.initOnloadTime(validTime, name);
							break;
						case "2":
							$(".alarm-time-day span:eq(1)").addClass("active");
							ctrl.initOnloadTime(validTime, name);
							break;
						case "3":
							$(".alarm-time-day span:eq(2)").addClass("active");
							ctrl.initOnloadTime(validTime, name);
							break;
						case "4":
							$(".alarm-time-day span:eq(3)").addClass("active");
							ctrl.initOnloadTime(validTime, name);
							break;
						case "5":
							$(".alarm-time-day span:eq(4)").addClass("active");
							ctrl.initOnloadTime(validTime, name);
							break;
						case "6":
							$(".alarm-time-day span:eq(5)").addClass("active");
							ctrl.initOnloadTime(validTime, name);
							break;
						case "7":
							$(".alarm-time-day span:eq(6)").addClass("active");
							ctrl.initOnloadTime(validTime, name);
							break;
					}
				};

				if (validTime["1"] && validTime["2"] && validTime["3"] && validTime["4"] && validTime["5"] && validTime["6"] && validTime["7"]) {

					$(".alarm-time-day span").removeClass("active");
					$(".alarm-time-day div").addClass("active");

					if (validTime["1"] == "00:00:00-23:59:59") {
						ctrl.set("isAll", false);
						$(".alarm-time-hours span").addClass("active");
					} else {
						ctrl.set("isAll", true);
						$(".alarm-time-hours span").removeClass("active");
					}

				} else {
					$(".alarm-time-day div").removeClass("active");

					if ((this.get("alarmStartTime") + "-" + this.get("alarmEndTime")) == "00:00:00-23:59:59") {
						$(".alarm-time-hours span").addClass("active");
						ctrl.set("isAll", false);
					} else {
						ctrl.set("isAll", true);
						$(".alarm-time-hours span").removeClass("active");

					}

				}

			},

			alarmTimeChange: Ember.observer("alarmStartTime", "alarmEndTime", function() {
				var alarmStartTime = this.get("alarmStartTime");
				var alarmEndTime = this.get("alarmEndTime");

				var reg = /^([0-1]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/;

				if (!reg.test(alarmStartTime)) {
					$(".alarm-time-hours input:first").addClass('active').siblings('input').removeClass('active');
					return;
				} else {
					$(".alarm-time-hours input:first").removeClass('active');
				};

				if (!reg.test(alarmEndTime)) {
					$(".alarm-time-hours input:last").addClass('active').siblings('input').removeClass('active');
					return;
				} else {
					$(".alarm-time-hours input:last").removeClass('active');
				};


				this.set("alarmTimeSlot", this.get("alarmStartTime") + " - " + this.get("alarmEndTime"));

			}),


			requireThresholds: function() {

				var ctrl = this,
					appId = this.get("business.id");
				if (!appId) {
					return;
				}
				var panelId = overviewOrCenterSwitch == "business" ? "business" : "system";

				this.store.ajax("GET", "alarms/" + appId + "/thresholds/" + panelId)
					.then(function(response) {
						var thresholds = [],
							tradings = [],
							algorithm = [];
						response.result.forEach(function(threshold) {
							ctrl._translateThresholdToLocal(threshold);
						});
						Ember.A(response.result).forEach(function(node) {
							if (!node.thresholdParam[0]) {
								node.thresholdParam[0] = {
									"indexName": "基线告警"
								};
								if (node.panelId == "system") {
									thresholds.push(node);

								} else {
									tradings.push(node);
								}
								return;
							}

							if (node.thresholdParam[0].indicator.indexOf("b") != -1) {
								tradings.push(node);
							} else {
								thresholds.push(node);
							}
						});


						if (ctrl.get("isShowSystemOrBusiness")) {
							ctrl.set("thresholds", Ember.A(thresholds));
						} else {
							ctrl.set("thresholds", Ember.A(tradings));
						}
					});
			},

			updateThreshold: function(threshold) {
				var ctrl = this,
					set = Ember.set,
					thresholdForm = this.get("thresholdForm"),
					curEditeThreshold = this.get("curEditeThreshold");;

				this._translateThresholdToLocal(threshold)
				set(curEditeThreshold, "targetId", threshold.targetId);
				set(curEditeThreshold, "thresholdType", threshold.thresholdType);
				set(curEditeThreshold, "thresholdParam", threshold.thresholdParam);
			},

			addThreshold: function(threshold) {
				this.get("thresholds").pushObject(this._translateThresholdToLocal(threshold));
			},

			validateAppForm: function() {
				var form = this.get("form");

				if ($.trim(form.name) == this.get("business.name") && $.trim(form.apdex_t) == this.get("business.apdex_t") && form.areaCode == this.get("business.areaCode")) {
					return false;
				}

				if (Ember.isBlank(form.name)) {
					return false;
				}

				if (Ember.isBlank(form.apdex_t)) {
					return false;
				}

				if (form.apdex_t && !/^[\d]+$|^\d*\.\d+$/.test(form.apdex_t)) {
					this.set("businessformTip", "apdex值必须为整数或小数！");
					return false;
				}

				this.set("businessformTip", null);
				return true;
			},

			resetForm: function() {
				this.set("form", {
					name: this.get("business.name") || "",
					apdex_t: this.get("business.apdex_t") || "",
					areaCode: this.get("business.areaCode")
				});
			},

			reset: function() {
				this.set("cancelSet", undefined);
			},

			_translateThresholdToLocal: function(threshold) {
				var indicatorNameMap = {
					rpm: "吞吐量上限",
					lrpm: "吞吐量下限",
					rtt: "系统响应时间",
					apdex: "系统Apdex",
					success: "系统成功率",
					error: "系统错误数"
				};
				var unitMap = {
					rpm: "rpm",
					lrpm: "rpm",
					rtt: "ms",
					apdex: "",
					success: "%",
					error: "%"
				};
				var tradingNameMap = {
					brpm: "交易量上限",
					blrpm: "交易量下限",
					brtt: "交易响应时间",
					bapdex: "交易Apdex",
					bsuccess: "交易成功率",
					berror: "交易错误数"
				};

				Ember.A(threshold.thresholdParam).forEach(function(tsParam) {
					if (threshold.thresholdType == "algorithm") {
						return;
					};
					if (tsParam.indicator.indexOf("b") != -1) {
						tsParam.indicatorName = tradingNameMap[tsParam.indicator] || "";
					} else {
						tsParam.indicatorName = indicatorNameMap[tsParam.indicator] || "";
					}
					tsParam.level_50 = tsParam.level["50"];
					tsParam.level_20 = tsParam.level["20"];
					tsParam.level_10 = tsParam.level["10"];
					tsParam.unit = unitMap[tsParam.indicator] || "";
				});

				return threshold;
			},

			actions: {
				addThreshold: function() {
					var ctrl = this,
						configThresholdView = Broada.getView("businessConfigThresholdView");
					this.set("curEditeThreshold", null);
					configThresholdView.newThresholdForm().openDialog();
				},

				// updateApp: function(){
				// 	var ctrl = this;
				// 	var form = ctrl.get("form");
				// 	if( !ctrl.validateAppForm() ){
				// 		return;
				// 	}
				// 	var data = Ember.merge({id: ctrl.get("business.id")}, ctrl.get("form"));
				// 	ctrl.store.ajax("PUT", "applications", data)
				// 	.then(function(response){
				// 		var app = ctrl.get("business");
				// 		Ember.set(app, "name", form.name);
				// 		Ember.set(app, "apdex_t", form.apdex_t);
				// 		Ember.set(app, "areaCode", form.areaCode);
				// 		alertTip("保存成功!");
				// 	});
				// },

				deleteApp: function() {
					var ctrl = this;
					confirmDialog("确定删除该应用吗?")
						.then(function() {
							ctrl.store.ajax("DELETE", "applications/" + ctrl.get("business.id"))
								.then(function() {
									alertTip("删除成功!");
									ctrl.transitionToRoute("business.center");
								});
						});
				},

				showThresholdsDiaolg: function(threshold) {

					this.set("curEditeThreshold", threshold);
					this.set("thresholdForm", Ember.copy(threshold, true));
					Ember.A(this.get("thresholdForm.thresholdParam"));

					Broada.getView("businessConfigThresholdsDialog").openDialog();
				},

				deleteThreshold: function(threshold) {
					var ctrl = this;
					confirmDialog("确定删除该阈值设置吗?")
						.then(function() {
							var panelId = overviewOrCenterSwitch == "business" ? "business" : "system";
							ctrl.store.ajax("DELETE", "alarms/" + ctrl.get("business.id") + "/thresholds/" + threshold.targetId + "/" + panelId + "/" + threshold.thresholdType)
								.then(function() {
									alertTip("删除成功!");
									ctrl.get("thresholds").removeObject(threshold);
								});
						});
				},

				updateAlarmTime: function() {

					var alarmStartTime = this.get("alarmStartTime"),
						alarmEndTime = this.get("alarmEndTime"),
						dateSelectData = {},
						ctrl = this,
						form = ctrl.get("form"),
						data = Ember.merge({
							id: ctrl.get("business.id")
						}, ctrl.get("form"));

					var reg = /^([0-1]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/;

					if (!reg.test(alarmStartTime)) {
						alert("时间格式不对,请以00:00:00时间格式输入");
					}

					if (!reg.test(alarmEndTime)) {
						alert("时间格式不对,请以00:00:00时间格式输入");
					}
					var i = 0;
					$(".alarm-time-day span").each(function() {
						if ($(this).hasClass("active")) {
							i = i + 1;
						}

					});

					$(".alarm-time-day span").each(function(index, item) {
						if ($(this).hasClass("active")) {
							if (!$(".alarm-time-hours span").hasClass("active")) {
								dateSelectData[index + 1] = alarmStartTime + "-" + alarmEndTime;
							} else {
								dateSelectData[index + 1] = "00:00:00-23:59:59";
							}

						};
						if (i == 7 || $(".alarm-time-day div").hasClass("active")) {
							if (!$(".alarm-time-hours span").hasClass("active")) {
								dateSelectData[index + 1] = alarmStartTime + "-" + alarmEndTime;
							} else {
								dateSelectData[index + 1] = "00:00:00-23:59:59";
							}
						}
					});

					data = Ember.merge(data, {
						validTime: JSON.stringify(dateSelectData)
					});

					ctrl.store.ajax("PUT", "applications", data)
						.then(function(response) {
							alertTip("保存成功!");
						});

				},

				cancelAlarmTime: function() {
					this.set("alarmStartTime", '00:00:00');
					this.set("alarmEndTime", '23:59:59');
					$(".alarm-time-day span").removeClass("active");
					this.resetForm();
				},

				dateSelectClick: function(returnField) {
					this.set("dateSelectData", returnField);
				}
			}
		});

		APM.BusinessDetailConfigController = BusinessDetailConfigController;
		return BusinessDetailConfigController;
	}
);